package com.beiding.my.bemapping;

import com.beiding.my.dtmapping.DtTypeMapper;
import com.google.common.base.Joiner;

import java.lang.reflect.Field;

public class BeFieldMapper implements BeAttributeMapper {

    //映射的 Be Mapper
    DtTypeMapper dtTypeMapper;

    //be对应的实体
    Field beFiled;

    //字段名称
    String name;

    private String id = Id.bof();

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void assignmentByAttributeName(Object bo, String[] segments, int currentSegment, Object v) {
        assignment(bo, v);
        if (currentSegment != segments.length - 1) {
            throw new RuntimeException("不符预期的参数长度:" + Joiner.on(".").join(segments) + "  应该:" + (currentSegment + 1) + " 实际:" + segments.length);
        }
    }

    @Override
    public void assignmentByAttributeId(Object bo, String[] segments, int currentSegment, Object v) {
        assignment(bo, v);
        if (currentSegment != segments.length - 1) {
            throw new RuntimeException("不符预期的参数长度:" + Joiner.on("_").join(segments) + Joiner.on("_").join(segments) + "  应该:" + (currentSegment + 1) + " 实际:" + segments.length);
        }
    }

    @Override
    public void fillExpressionDetails(Class type, String[] segments, int currentSegment, ExpressionDetails expressionDetails) {
        expressionDetails.set(this.name, this.id);
        if (currentSegment != segments.length - 1) {
            throw new RuntimeException("不符预期的参数长度:" + Joiner.on("_").join(segments) + Joiner.on(".").join(segments) + "  应该:" + (currentSegment + 1) + " 实际:" + segments.length);
        }
    }

    private void assignment(Object bo, Object v) {
        try {
            Object be = beFiled.get(bo);
            if (be == null) {
                be = dtTypeMapper.newDt();
                beFiled.set(bo, be);
            }
            //这里依然使用名称赋值
            dtTypeMapper.assignmentByFieldName(be, name, v);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
